#!/bin/bash

###
### This script unzips and installs Glassfish and MariaDB in 
### the current working directory.
### Afterwards both are configured and the App developed by
### the simsearch1 team is deployed.
###
### To start the Glassfish server, MariaDB and to publish the 
### App, please use the start script.
###
### @Author: Florian Sieck
###

echo "This script will setup the environment and configure the simsearch1 App. This may take several minutes."
 
mkdir "SimSearch1"

pushd "SimSearch1" > /dev/null

echo "Unzipping Glassfish 4.0"
unzip ../tools/glassfish-4.0.zip > /dev/null

echo "Extracting MariaDB"
tar -xf ../tools/mariadb-5.5.34-linux-i686.tar.gz > /dev/null
mv mariadb-5.5.34-linux-i686 mariadb
ln -s mariadb mysql

echo "Creating DB data folder"
mkdir ${HOME}/simSearch1Mysql
mkdir ${HOME}/simSearch1Mysql/data
cp ../mysql-cnf/.my.cnf mysql/.my.cnf
sed -e "s#REPLACEHOME#$HOME#g" ../mysql-cnf/.my.cnf > mysql/.my.cnf 

echo "Copy config files to Glassfish server domain1"
rm -r glassfish4/glassfish/domains/domain1/config
cp -r ../config glassfish4/glassfish/domains/domain1/config

echo "Configuring database"
pushd mysql > /dev/null
./scripts/mysql_install_db --defaults-file=".my.cnf" --basedir="."
#pushd bin > /dev/null
echo "Starting up MariaDB"
./bin/mysqld_safe --defaults-file=".my.cnf" &
sleep 10s
echo "Adding tables"
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/create_dbuser.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/create_simsearchusermgmt.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/create_contentmanagementdb.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/grantprivileges.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/createcontmgmtdbtables.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/createusermgmtdbtables.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/view.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/addroles.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/addadmin.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/defaultcategorys.sql
./bin/mysql --defaults-file=".my.cnf" --user="root" < ../../sql-scripts/defaultpreferences.sql
#popd > /dev/null
popd > /dev/null

echo "Deploying the Application"
./glassfish4/glassfish/bin/asadmin start-domain
./glassfish4/glassfish/bin/asadmin deploy ../application/SimilaritySearchEAR.ear
./glassfish4/glassfish/bin/asadmin stop-domain 

pushd mysql > /dev/null 
./bin/mysqladmin --defaults-file=".my.cnf" --user="root" shutdown
popd > /dev/null

popd > /dev/null
